package com.bjpowernode.crm.workbench.web.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.bjpowernode.crm.commons.constant.AppConstant;
import com.bjpowernode.crm.commons.enums.RespCode;
import com.bjpowernode.crm.commons.resp.Result;
import com.bjpowernode.crm.commons.utils.UUIDUtils;
import com.bjpowernode.crm.settings.domain.DicValue;
import com.bjpowernode.crm.settings.domain.User;
import com.bjpowernode.crm.settings.service.DicValueService;
import com.bjpowernode.crm.settings.service.UserService;
import com.bjpowernode.crm.workbench.domain.Activity;
import com.bjpowernode.crm.workbench.domain.Clue;
import com.bjpowernode.crm.workbench.domain.ClueActivityRelation;
import com.bjpowernode.crm.workbench.domain.ClueRemark;
import com.bjpowernode.crm.workbench.service.ActivityService;
import com.bjpowernode.crm.workbench.service.ClueActivityRelationService;
import com.bjpowernode.crm.workbench.service.ClueRemarkService;
import com.bjpowernode.crm.workbench.service.ClueService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * ClassName:ClueController
 * Package:com.bjpowernode.crm.workbench.web.controller
 * Date:2022/6/13 9:28
 * Description:
 * Author:zsm@zhangshuming.com
 */
@Controller
public class ClueController {
    @Autowired
    private ClueActivityRelationService clueActivityRelationService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private ClueRemarkService clueRemarkService;
    @Autowired
    private DicValueService dicValueService;
    @Autowired
    private ClueService clueService;
    @Autowired
    private UserService userService;

    @RequestMapping("/workbench/clue/index.do")
    public String index(HttpServletRequest request) {
        // 获取线索来源数据
        List<DicValue> sourceList = dicValueService.queryDicValueListByTypeCode("source");
        request.setAttribute("sourceList", sourceList);
        // 获取线索状态数据
        List<DicValue> clueStateList = dicValueService.queryDicValueListByTypeCode("clueState");
        request.setAttribute("clueStateList", clueStateList);
        // 获取所有者
        List<User> userList = userService.queryAllUserList();
        request.setAttribute("userList", userList);
        // 获取称呼列表
        List<DicValue> appellationList = dicValueService.queryDicValueListByTypeCode("appellation");
        request.setAttribute("appellationList", appellationList);
        return "workbench/clue/index";
    }

    @RequestMapping("/workbench/clue/queryClueList.do")
    @ResponseBody
    public Result queryClueList(@RequestParam(value = "pageNo") Integer pageNo,
                                @RequestParam(value = "pageSize") Integer pageSize,
                                @RequestParam(value = "fullName", required = false) String fullName,
                                @RequestParam(value = "phone", required = false) String phone,
                                @RequestParam(value = "mphone", required = false) String mphone,
                                @RequestParam(value = "company", required = false) String company,
                                @RequestParam(value = "ownerName", required = false) String ownerName,
                                @RequestParam(value = "source", required = false) String source,
                                @RequestParam(value = "state", required = false) String state
    ) {
        Result result = Result.FRR();


        try {
            // 分页查询列表数据
            PageHelper.startPage(pageNo, pageSize);

            // 列表数据
            // 查询条件
            Map<String, Object> param = new HashMap<>();
            param.put("fullName", fullName);
            param.put("phone", phone);
            param.put("mphone", mphone);
            param.put("company", company);
            param.put("ownerName", ownerName);
            param.put("source", source);
            param.put("state", state);
            List<Clue> clueList = clueService.queryClueListByCondition(param);
            // 封装分页对象
            PageInfo<Clue> pageInfo = new PageInfo<>(clueList);
            // 成功
            result.setRespCode(RespCode.SUCCESS);
            // 判断是否有数据
            if (ObjectUtil.isNull(pageInfo.getList()) || pageInfo.getList().size() == 0) {
                result.setRespCode(RespCode.QUER_NO_DATE);
            } else {
                result.setBody(pageInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }

    @RequestMapping("/workbench/clue/saveCreateClue.do")
    @ResponseBody
    public Result saveCreateClue(Clue clue, HttpServletRequest request) {
        Result result = Result.FRR();

        User userSession = (User) request.getSession().getAttribute(AppConstant.SESSION_USER);
        try {
            // 添加线索信息
            // 完善对象信息
            clue.setId(UUIDUtils.getUUID());
            clue.setCreateTime(DateUtil.formatDateTime(new Date()));
            clue.setCreateBy(userSession.getId());
            clueService.saveCreatClue(clue);
            result.setRespCode(RespCode.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }

    @RequestMapping("workbench/clue/editClueById.do")
    @ResponseBody
    public Result editClueById(String clueId) {
        Result result = Result.FRR();
        try {
            // 根据id查询数据
            Clue clue = clueService.queryClueById(clueId);
            result.setRespCode(RespCode.SUCCESS);
            result.setBody(clue);
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }

        return result;
    }

    @RequestMapping("/workbench/clue/saveEditClue.do")
    @ResponseBody
    public Result saveEditClue(HttpServletRequest request, Clue clue) {
        Result result = Result.FRR();
        User userSession = (User) request.getSession().getAttribute(AppConstant.SESSION_USER);
        try {
            // 完善信息
            clue.setEditTime(DateUtil.formatDateTime(new Date()));
            clue.setEditBy(userSession.getId());
            // 更新线索列表数据
            clueService.saveEditClue(clue);
            result.setRespCode(RespCode.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }

    @RequestMapping("/workbench/clue/deleteClueByIds.do")
    @ResponseBody
    public Result deleteClueByIds(@RequestParam(value = "id") String[] ids) {
        Result result = Result.FRR();
        try {
            // 通多id删除线索列表
            clueService.deleteClueByIds(ids);
            result = Result.SUCCESS();
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }

    @RequestMapping("workbench/clue/detailClue.do")
    public String detailClue(HttpServletRequest request, String id) {
        // 按照id查询详情页信息
        Clue clue = clueService.queryClueDetaiById(id);
        request.setAttribute("clue", clue);

        return "workbench/clue/detail";
    }

    @RequestMapping("workbench/clue/queryClueRemarkList.do")
    @ResponseBody
    public Result queryClueRemarkList(String clueId) {
        Result result = Result.FRR();
        try {
            // 获取线索详情备注信息
            List<ClueRemark> clue = clueRemarkService.queryClueRemarkList(clueId);
            result = Result.SUCCESS();
            result.setBody(clue);
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }

    @RequestMapping("/workbench/clue/saveCreateClueRemarkBtn.do")
    @ResponseBody
    public Result saveCreateClueRemarkBtn(HttpServletRequest request, ClueRemark clueRemark) {
        Result result = Result.FRR();
        User sessionUser = (User) request.getSession().getAttribute(AppConstant.SESSION_USER);
        try {
            // 完善信息
            clueRemark.setId(UUIDUtils.getUUID());
            clueRemark.setCreateTime(DateUtil.formatDateTime(new Date()));
            clueRemark.setCreateBy(sessionUser.getId());
            // 根据id新增备注内容
            clueRemarkService.saveCreateClueRemarkBtn(clueRemark);
            result = Result.SUCCESS();

        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }

    @RequestMapping("/workbench/clue/editClueRemark.do")
    @ResponseBody
    public Result editClueRemark(ClueRemark clueRemark, HttpServletRequest request) {
        Result result = Result.FRR();
        User sessionUser = (User) request.getSession().getAttribute(AppConstant.SESSION_USER);
        try {
            // 完善信息
            clueRemark.setEditTime(DateUtil.formatDateTime(new Date()));
            clueRemark.setEditBy(sessionUser.getId());
            // 更新线索详情备注
            clueRemarkService.editClueRemark(clueRemark);
            result = Result.SUCCESS();
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }

    @RequestMapping("/workbench/clue/deleteClueRemark.do")
    @ResponseBody
    public Result deleteClueRemark(String id) {
        Result result = Result.SUCCESS();
        try {
            // 根据id删除线索详情备注
            clueRemarkService.deleteClueRemark(id);
            result = Result.SUCCESS();
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }


    @RequestMapping("/workbench/clue/queryActivityByClueId.do")
    @ResponseBody
    public Result queryActivityByClueId(String clueId) {
        Result result = Result.SUCCESS();
        try {
            // 根据id查询线索参与的市场活动
            List<Activity> activityList = activityService.queryActivityByClueId(clueId);
            result = Result.SUCCESS();
            result.setBody(activityList);
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }

    @RequestMapping("/workbench/clue/searchActivityByClueId.do")
    @ResponseBody
    public Result searchActivityByClueId(String clueId,String searchActivityName){
        Result result = Result.FRR();
        try {
            // 根据条件模糊查询关联市场活动
            List<Activity> activityList = activityService.querysearchActivityByClueId(clueId,searchActivityName);
            result = Result.SUCCESS();
            result.setBody(activityList);
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }


    @RequestMapping("/workbench/clue/saveBindActivityBtn.do")
    @ResponseBody
    public Result saveBindActivityBtn(@RequestParam("id") String[] ids,String clueId){
        Result result = Result.FRR();
        // 准备集合来接收所有要创建的对象
        List<ClueActivityRelation> clueActivityRelationList = new ArrayList<>();
        // 准备对象ClueActivityRelation用来放数据
        ClueActivityRelation clueActivityRelation = null;
        try {
            // 循环遍历所有的id，
            for (String id : ids){
                // 每遍历一组创建一个对象
                clueActivityRelation = new ClueActivityRelation();
                clueActivityRelation.setId(UUIDUtils.getUUID());
                clueActivityRelation.setActivityId(id);
                clueActivityRelation.setClueId(clueId);
                // 将对象添加到list集合
                clueActivityRelationList.add(clueActivityRelation);
            }
            // 关联市场活动
            clueActivityRelationService.saveBindActivityBtn(clueActivityRelationList);
            result = Result.SUCCESS();
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }

    @RequestMapping("/workbench/clue/deleteClueCorrelate.do")
    @ResponseBody
    public Result deleteClueCorrelate(String activityId,String clueId){
        Result result = Result.FRR();
        try {
            // 根据id解除市场活动线索关联
            activityService.deleteClueCorrelate(activityId,clueId);
            result = Result.SUCCESS();
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }

        return result;
    }

    @RequestMapping("/workbench/clue/convertPage.do")
    public String convertPage(HttpServletRequest request,String id){
        Clue clue = clueService.queryClueDetaiById(id);
        request.setAttribute("clue",clue);
        List<DicValue> stageList = dicValueService.queryDicValueListByTypeCode("stage");
        request.setAttribute("stageList",stageList );
        return "workbench/clue/convert";
    }

    @RequestMapping("/workbench/clue/queryClueActivityByIdList.do")
    @ResponseBody
    public Result queryClueActivityByIdList(String clueId,String searchActivityText){
        Result result = Result.FRR();
        try {
            // 查询线索参与的市场活动
            List<Activity> activityList = activityService.queryClueActivityByIdList(clueId,searchActivityText);
            result = Result.SUCCESS();
            result.setBody(activityList);
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }

    @RequestMapping("/workbench/clue/convert.do")
    @ResponseBody
    public Result convert(HttpServletRequest request,
                             String clueId,
                             Boolean isCreateTransaction,
                             String amountOfMoney,
                             String tradeName,
                             String expectedClosingDate,
                             String stage,
                             String activityId){
        Result result =Result.FRR();
        User sessionUser = (User) request.getSession().getAttribute(AppConstant.SESSION_USER);
        try {
            // 线索的转换

            Map<String,Object> param = new HashMap<>();
            param.put("clueId",clueId);
            param.put("isCreateTransaction",isCreateTransaction);
            param.put("amountOfMoney",amountOfMoney);
            param.put("tradeName",tradeName);
            param.put("expectedClosingDate",expectedClosingDate);
            param.put("stage",stage);
            param.put("activityId",activityId);
            param.put("sessionUser",sessionUser);
            clueService.saveVConvert(param);
            result = Result.SUCCESS();
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }
}
